package com.mairuide.excel_rule.service;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.mairuide._frame.utils.excellistener.AnalysisExcelRuleExcelListener;
import com.mairuide.excel_rule.dao.ExcelRuleDao;
import com.mairuide.excel_rule.pojo.ExcelRule;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description
 * @auther 刘中华
 * @create 2019-03-21 17:28
 */
@Service
public class ExcelRuleService {
    @Autowired
    private ExcelRuleDao excelRuleDao;

    /**
     * @Author 刘中华
     * @Date 2019/3/21 9:59
     * @Param [titleHead]
     * @return com.mairuide.excel_rule.pojo.ExcelRule
     * @Description 根据标题头返回对应的规则
     **/
    public List<ExcelRule> getExcelRuleByTitleHead(String titleHead){
        List<ExcelRule> byTitleHead = excelRuleDao.findByTitleHead(titleHead);
        if (byTitleHead!=null&&byTitleHead.size()>0){
            return byTitleHead;
        }
        return null;
    }
    /**
     * @Author 刘中华
     * @Date 2019/3/21 10:02
     * @Param []
     * @return java.util.List<java.lang.String>
     * @Description 返回标题头的所有集合
     **/
    public List<String> getTitleHeadList(){
        List<ExcelRule> all = (List<ExcelRule>) excelRuleDao.findAll();
        List<String> collect = all.stream().map(m -> m.getTitleHead()).collect(Collectors.toList());
        return collect;
    }
    /**
     * @Author 刘中华
     * @Date 2019/3/22 9:17
     * @Param [file]
     * @return com.mairuide.excel_rule.pojo.ExcelRule
     * @Description 通过文件名得到对应的规则
     * 解析规则：默认只读取文件的前10行
     **/
    public ExcelRule getExcelRuleByFile(InputStream inputStream,String filename) throws Exception{
        AnalysisExcelRuleExcelListener excelListener = new AnalysisExcelRuleExcelListener();
        excelListener.setFilename(filename);
        ExcelReader excelReader = EasyExcelFactory.getReader(inputStream,excelListener);
        List<com.alibaba.excel.metadata.Sheet> sheets = excelReader.getSheets();
        for (int i=0;i<sheets.size();i++) {
            excelReader.read(sheets.get(i));
        }
        inputStream.close();
        return excelListener.getExcelRule();
    }

    public ExcelRule findExcelRuleById(Integer id){
        return excelRuleDao.findById(id);
    }

    /**
     * @Author 刘中华
     * @Date 2019/4/11 11:28
     * @Param [excelRule]
     * @return com.mairuide.excel_rule.pojo.ExcelRule
     * @Description  新增/修改 规则
     **/
    public ExcelRule addExcelRule(ExcelRule excelRule){
        ExcelRule save = null ;
        if (excelRule.getId()!=null){
            excelRule.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        }else{
            excelRule.setCreateTime(new Timestamp(System.currentTimeMillis()));
            excelRule.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        }
        save = excelRuleDao.save(excelRule);
        return save;
    }

    /**
     * @Author 刘中华
     * @Date 2019/4/11 11:31
     * @Param [id]
     * @return void 删除规则
     * @Description
     **/
    public void delExcelRule(Integer id){
        excelRuleDao.delete(id);
    }

    /**
     * @Author 刘中华
     * @Date 2019/4/11 11:31
     * @Param [id]
     * @return  查找全部的规则
     * @Description
     **/
    public Page<ExcelRule> getExcelRuleList(ExcelRule excelRule){
        Sort sort = new Sort(Sort.Direction.DESC,"id");
        PageRequest pageRequest = new PageRequest(0,Integer.MAX_VALUE,sort);
        Specification<ExcelRule> specification = createSpecification(excelRule);
        //List<ExcelRule> all = (List<ExcelRule>)excelRuleDao.findAll();
        return excelRuleDao.findAll(specification, pageRequest);
    }

    /**
     * 动态条件构建
     * @param searchMap
     * @return
     */
    private Specification<ExcelRule> createSpecification(ExcelRule excelRule) {
        return new Specification<ExcelRule>() {
            @Override
            public Predicate toPredicate(Root<ExcelRule> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<Predicate>();
                // 案件名称
                if (excelRule!=null&&StringUtils.isNotBlank(excelRule.getTemplateName())) {
                    predicateList.add(cb.like(root.get("templateName").as(String.class), "%"+excelRule.getTemplateName()+"%"));
                }
                return cb.and( predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }
}
